<template>
  <div class="app-container editcss">
    <div class="dheight">
      <div class="titleHeight">
        <el-row>
          <el-col>
            <el-button type="primary" class="mb15" size="small" icon="el-icon-plus" v-repeatStop="{ func: add, delay: '2000' }" style="float: left;margin-right: 10px;">
              新增
            </el-button>
            <screenSelect title="区域名称" type='input' v-model="queryFrom.name" :isValue='queryFrom.name' placeholder="请输入"
              @transfer="valueHeld($event, 'name')" class=" mb15" width="200px" style="float: left;" />
            <!-- <el-col :span="6">
                <screenSelect title="所属电站" type='select' v-model="queryFrom.base_station_id"
                  :isValue='queryFrom.base_station_id' placeholder="请选择"
                  @transfer="valueHeld($event, 'base_station_id')" :options="queryoptions" class=" mb15" />
              </el-col> -->
            
            <el-button type="primary" class="mb15" size="small" icon="el-icon-search" v-repeatStop="{ func: search, delay: '2000' }">
              搜索
            </el-button>
            <el-button type="primary" class="mb15" size="small" icon="el-icon-refresh-left" v-repeatStop="{ func: reset, delay: '2000' }">
              重置
            </el-button>
            <!-- <el-button type="warning" class="ch_button " :disabled="isDerive" @click="derive">
              <i class="el-icon-download"></i>
              <div>导入</div>
            </el-button>
            <el-button type="success" class="ch_button " :disabled="isDeriveout" @click="deriveout">
              <i class="el-icon-upload2"></i>
              <div>导出</div>
            </el-button> -->
          </el-col>
        </el-row>


      </div>
      <el-table :data="tableData" border style="width: 100%" :height="endHeight" v-loading="loading"
        element-loading-text="Loading..." element-loading-spinner="el-icon-loading">
        <el-table-column type="index" label="序号" width="50" align="center">
        </el-table-column>
        <el-table-column label="区域名称" min-width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="所属电站" min-width="150" align="center">
          <template slot-scope="scope">
            {{ scope.row.base_station.name }}
          </template>
        </el-table-column>
        <el-table-column label="设备数" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.equCount }}
          </template>
        </el-table-column>
        <el-table-column label="设备正常数" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.equNormal }}
          </template>
        </el-table-column>
        <el-table-column label="设备故障数" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.equQuestion }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="保护状态" min-width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.powerstationprotect }}
          </template>
        </el-table-column> -->
        <el-table-column label="地址" min-width="200" align="center">
          <template slot-scope="scope">
            {{ scope.row.address }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <div class="operation_box">
              <el-button @click.native.prevent="editRow(scope.row)" type="text" class="operation_edit" size="mini">
                编辑
              </el-button>
              <el-button @click.native.prevent="viewRow(scope.row)" type="text" class="operation_view" size="mini">
                查看
              </el-button>
              <!-- <el-button @click.native.prevent="deleteRow(scope.row)" type="text" class="operation_delete" size="mini">
                删除
              </el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="paginationblock" v-if="total > 0">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="pageData.page" :page-sizes="[10, 20, 30, 40]" :page-size="pageData.limit" :background="true"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <adddistrict v-if="dialogFormVisible" :enterpriseoptions="enterpriseoptions"
        :powerstationoptions="powerstationoptions" :optionVal="addfrom" :dialogFormVisible.sync="dialogFormVisible"
        @updata="cancel" @addupdata="addupdatasave">
      </adddistrict>
      <viewdistrict v-if="dialogViewVisible" :enterpriseoptions="enterpriseoptions"
        :powerstationoptions="powerstationoptions" :optionVal="addfrom" :dialogViewVisible.sync="dialogViewVisible"
        @viewHeld="viewHeld">
      </viewdistrict>
    </div>
  </div>
</template>

<script>
import screenSelect from '@/components/screenSelect/index.vue';
import adddistrict from './components/adddistrict.vue';
import viewdistrict from './components/viewdistrict.vue';
import { getregionList, addto, update } from '@/api/district.js'
import { getbaseList } from '@/api/powerstation.js'
import { getqiyeList, getDianzhanList } from '@/api/common.js'
export default {
  name: 'WorkspaceJsonDistrict',
  components: {
    screenSelect,
    adddistrict,
    viewdistrict
  },
  data() {
    return {
      dialogFormVisible: false,
      dialogViewVisible: false,
      isDerive: false,
      isDeriveout: false,
      queryFrom: {},
      endHeight: 0,
      pageData: {
        page: 1,
        limit: 10
      },
      total: 0,
      tableData: [],
      loading: true,
      queryoptions: [],
      powerstationoptions: [],
      addfrom: {},
      enterpriseoptions: []
    };
  },

  mounted() {
    this.fetTableHeight()
    this.getList()
    this.getQiye()
  },

  methods: {
    getQiye() {
      let that = this
      let data = {}
      data.type = 1
      getqiyeList(data).then(res => {
        if (res.code == 200) {
          res.data.map(item => {
            item.label = item.name
            item.value = item.id
          })
          that.enterpriseoptions = res.data
        }
      })
    },
    getList(data) {
      let that = this
      if (data) {
        getregionList(data).then(res => {
          if (res.code == 200) {
            console.log(res.data);
            that.total = res.data.count
            that.tableData = res.data.rows
            that.loading = false
          } else {
            that.$modal.msgError(res.message)
          }
        })
      } else {
        getregionList(that.pageData).then(res => {
          if (res.code == 200) {
            console.log(res.data);
            that.total = res.data.count
            that.tableData = res.data.rows
            that.loading = false
          } else {
            that.$modal.msgError(res.message)
          }
        })
      }

      // getbaseList().then(res => {
      //   if (res.code == 200) {
      //     res.data.rows.map(item => {
      //       item.label = item.name
      //       item.value = item.id
      //     })
      //     that.queryoptions = res.data.rows
      //   } else {
      //     that.$modal.msgError(res.message)
      //   }
      // })
    },
    retfundata(data, iv) {
      let str = ''
      data.map(item => {
        if (item.id == iv) {
          str = item.name
        }
      })
      return str
    },
    cancel(e) {
      this.dialogFormVisible = e.dialogFormVisible
      this.addfrom = e.form
    },
    addupdatasave(e) {
      let that = this
      if (e.form.id) {
        update(e.form).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.message)
            this.dialogFormVisible = e.dialogFormVisible
            this.getList()
          } else {
            that.$modal.msgError(res.message)
          }
        })
      } else {
        addto(e.form).then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess(res.message)
            this.dialogFormVisible = e.dialogFormVisible
            this.getList()
          } else {
            that.$modal.msgError(res.message)
          }
        })
      }
    },
    add() {
      this.addfrom = {
        admin_id: '',
      }
      this.dialogFormVisible = true
    },
    editRow(row) {
      this.addfrom = JSON.parse(JSON.stringify(row))
      this.addfrom.admin_id = this.addfrom.base_station.admin_id
      console.log(this.addfrom);
      this.dialogFormVisible = true
    },
    viewHeld(e) {
      this.dialogViewVisible = e
    },
    viewRow(row) {
      this.addfrom = JSON.parse(JSON.stringify(row))
      this.dialogViewVisible = true
      console.log(row, '查看');
    },
    deleteRow(row) {
      console.log(row, '删除');
      this.$confirm('此操作将永久删除' + row.districtname + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: false,
      }).then(() => {
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
        this.$modal.msg('已取消删除')
      });
    },
    search() {
      this.pageData = {
        page: 1,
        limit: 10
      }
      this.loading = true
      let data = this.mergeObjects(this.pageData, this.queryFrom)
      this.getList(data)
      console.log(this.queryFrom);
    },
    reset() {
      this.queryFrom = {
        name: '',
        base_station_id: ''
      }
    },
    mergeObjects(obj1, obj2) {
      return Object.assign({}, obj1, obj2);
    },
    //导入
    derive() {
      this.isDerive = true
      // getTimeExpor(this.queryFrom).then(res => {
      //   const link = document.createElement('a')
      //   const blob = new Blob([res.data], {
      //     type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      //   })
      //   console.log(res);
      //   const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1].substring(7));
      //   link.setAttribute('download', fileName)
      //   link.style.display = 'none'
      //   link.href = URL.createObjectURL(blob)
      //   link.click()
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // }).catch(err => {
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // })
      setTimeout(() => {
        this.isDerive = false
      }, 5000)
    },
    //导出
    deriveout() {
      this.isDeriveout = true
      // getTimeExpor(this.queryFrom).then(res => {
      //   const link = document.createElement('a')
      //   const blob = new Blob([res.data], {
      //     type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      //   })
      //   console.log(res);
      //   const fileName = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1].substring(7));
      //   link.setAttribute('download', fileName)
      //   link.style.display = 'none'
      //   link.href = URL.createObjectURL(blob)
      //   link.click()
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // }).catch(err => {
      //   setTimeout(() => {
      //     this.isDerive = false
      //   }, 5000)
      // })
      setTimeout(() => {
        this.isDeriveout = false
      }, 5000)
    },
    resetHeight() {
      return new Promise((resolve, reject) => {
        this.endHeight = 0
        resolve()
      })
    },
    fetTableHeight() {
      this.resetHeight().then(res => {
        let fHeight = (window.getComputedStyle(document.querySelector('.editcss')).height).replace('px', "")
        let zHeight = (window.getComputedStyle(document.querySelector('.titleHeight')).height).replace('px', "")
        this.endHeight = (fHeight - zHeight - 92)
      })
    },
    handleSizeChange(val) {
      this.pageData.limit = val
      
      this.loading = true
      let data = this.mergeObjects(this.pageData, this.queryFrom)
      this.getList(data)
    },
    handleCurrentChange(val) {
      this.pageData.page = val
      
      this.loading = true
      let data = this.mergeObjects(this.pageData, this.queryFrom)
      this.getList(data)
    },
    valueHeld(childParam, fatherparam) {
      this.queryFrom[fatherparam] = childParam
    },
  },
};
</script>

<style lang="scss" scoped>
.dheight {
  // box-shadow: 0 0 10px #BBBBBB;
  border-radius: 6px;
  // padding: 20px;
  height: calc(100%);
  position: relative;
}

::v-deep .el-button.ch_button {
  padding: 7px 9px;
}

::v-deep .el-button.ch_button span {
  display: flex;
  align-items: center;

  i {
    font-size: 16px;
  }

  div {
    font-size: 13px;
    font-weight: 400;
    margin-left: 4px;
  }
}
</style>